//: CheckoutAction.java 10.09.2008 16:06:44Z apt $
package com.devunion.salon.web.action;

import com.devunion.salon.core.enumeration.PaymentMethodHandler;
import com.devunion.salon.persistence.*;
import com.devunion.salon.persistence.dao.*;
import com.devunion.salon.util.DateFormatter;
import com.devunion.salon.web.bean.*;
import com.devunion.salon.web.form.CheckoutEditForm;
import com.devunion.salon.web.form.CheckoutForm;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Timoshenko Alexander
 */
public class CheckoutAction extends CoreAction {
    private ChequeDao chequeDao;
    private DayDao dayDao;
    private EmployeeDao employeeDao;
    private CustomerDao customerDao;
    private CashInOutDao cashInOutDao;
    private PaymentMethodHandler paymentMethodHandler;

    public void setChequeDao(ChequeDao chequeDao) {
        this.chequeDao = chequeDao;
    }

    public void setDayDao(DayDao dayDao) {
        this.dayDao = dayDao;
    }

    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

    public void setCustomerDao(CustomerDao customerDao) {
        this.customerDao = customerDao;
    }

    public void setPaymentMethodHandler(PaymentMethodHandler paymentMethodHandler) {
        this.paymentMethodHandler = paymentMethodHandler;
    }

    public void setCashInOutDao(CashInOutDao cashInOutDao) {
        this.cashInOutDao = cashInOutDao;
    }

    public ActionForward welcome(ActionMapping actionMapping, ActionForm actionForm,
                                 HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        CheckoutForm form = (CheckoutForm) actionForm;
        form.getTransactions().clear();
        form.getCashes().clear();
        String selectAll = resources.getMessage("checkout.all.select.option");

        Collection<Employee> employees = employeeDao.getEmployees(getUsername());
        form.getEmployees().add(new LabelValueBean(selectAll, ""));
        for (Employee employee : employees) {
            form.getEmployees().add(new LabelValueBean(employee.getFirstName() + " " + employee.getLastName(), employee.getId().toString()));
        }

        Collection<Customer> customers = customerDao.loadAll();
        form.getCustomers().add(new LabelValueBean(selectAll, ""));
        if (customers != null) {
            for (Customer customer : customers) {
                form.getCustomers().add(new LabelValueBean(customer.getFirstName() + " " + customer.getLastName(), customer.getId().toString()));
            }
        }

        Collection<Cheque> cheques = chequeDao.getByDate(DateFormatter.getSQLDate(form.getHiddenDate()), getUsername(),
                form.getSelectedEmployee(), form.getSelectedCustomer());
        List<PaymentBean> payments = new ArrayList<PaymentBean>();
        for (Cheque cheque : cheques) {
            ChequeBean bean = new ChequeBean(cheque);
            if (cheque.getTransactions() != null) {
                for (Transaction transaction : cheque.getTransactions()) {
                    TransactionBean transactionBean = new TransactionBean();
                    transactionBean.setTransNumber(transaction.getNumber());
                    if (transaction.getEmployee() != null) {
                        EmployeeBean employeeBean = new EmployeeBean(transaction.getEmployee());
                        if (!bean.getEmployees().contains(employeeBean)) {
                            bean.getEmployees().add(employeeBean);
                        }
                        transactionBean.setEmployee(employeeBean);
                    }
                    if (transaction.getProduct() != null) {
                        ProductBean productBean = new ProductBean(transaction.getProduct());
                        transactionBean.setProduct(productBean);                        
                    } else if (transaction.getService() != null) {
                        transactionBean.setService(new ServiceBean(transaction.getService()));
                    } else if (transaction.getGiftCard() != null) {
                        GiftcardBean giftcardBean = new GiftcardBean();
                        giftcardBean.setAmount(Float.valueOf(transaction.getGiftCard().getAmount()));
                        giftcardBean.setTaxes(0f);
                        giftcardBean.setName(resources.getMessage("modal.add.transaction.payment.giftcard").toLowerCase());
                        transactionBean.setGiftcardBean(giftcardBean);
                    }
                    transactionBean.setQuantity(transaction.getQuantity());                    
                    bean.getTransactions().add(transactionBean);
                }
            }
            
            bean.setCustomerBean(cheque.getCustomer() != null ? new CustomerBean(cheque.getCustomer()) :
                    new CustomerBean());
            if(bean.getPayment()!=null){
                payments.add(bean.getPayment());
            }
            if(bean.getSecondPayment()!=null){
                payments.add(bean.getSecondPayment());
            }
            bean.setDiscount(cheque.getDiscount());
            form.getTransactions().add(bean);
        }

        Collection<CashInOut> caches = cashInOutDao.getCashByDate(DateFormatter
                            .getSQLDate(form.getHiddenDate()), getUsername());
        if(caches!=null && caches.size()>0){
            for(CashInOut cashInOut: caches){
                form.getCashes().add(new CashInOutBean(cashInOut));
                payments.add(new PaymentBean(cashInOut.getPayment()));
            }
        }

        Float totalCheck =0f, totalGiftcard = 0f, totalCards = 0f, totalCach =0f;
        for(PaymentBean paymentBean: payments){
            if(paymentMethodHandler.containsCach(paymentBean.getMethod())){
                totalCach+=paymentBean.getAmount();
            }else if(paymentMethodHandler.containsCard(paymentBean.getMethod())){
                totalCards+=paymentBean.getAmount();
            }else if(paymentMethodHandler.containsCheck(paymentBean.getMethod())){
                totalCheck+=paymentBean.getAmount();
            }else if(paymentMethodHandler.containsGiftcard(paymentBean.getMethod())){
                totalGiftcard+=paymentBean.getAmount();
            }else if(paymentBean.getMethod().equalsIgnoreCase("cashin")){
                totalCach+=paymentBean.getAmount();
            }else if(paymentBean.getMethod().equalsIgnoreCase("cashout")){
                totalCach-=paymentBean.getAmount();
            }
        }


        Day day = dayDao.getDay(DateFormatter.getSQLDate(form.getHiddenDate()), getUsername());

        if(day == null){
            form.setIsStarted(null);
        }else if(day.getEnded() == null || day.getEnded() == Boolean.FALSE){
            form.setIsStarted(Boolean.TRUE);
            form.setStartDay(day.getStart());
            totalCach+=day.getStart();
        }else{
            form.setIsStarted(Boolean.FALSE);
            form.setStartDay(day.getStart());
            totalCach+=day.getStart();
        }

        form.setTotalCash(totalCach);
        form.setTotalCheck(totalCheck);
        form.setTotalCredit(totalCards);
        form.setTotalGiftcard(totalGiftcard);

        if(httpServletRequest.getSession().getAttribute("transaction")!=null){
            httpServletRequest.getSession().removeAttribute("transaction");
        }
        
        return actionMapping.findForward("success");
    }

    public ActionForward delete(ActionMapping actionMapping, ActionForm actionForm,
                                 HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        CheckoutForm form =(CheckoutForm)actionForm;
        String number = form.getNumber();

        if(!StringUtils.isBlank(number)){
            Cheque cheque = chequeDao.getByNumber(number);
            if(cheque!= null){
                chequeDao.delete(cheque);
            }
        }

        return actionMapping.findForward("success"); 
    }

    public ActionForward edit(ActionMapping actionMapping, ActionForm actionForm,
                                 HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        CheckoutEditForm form =(CheckoutEditForm)actionForm;
        String number = form.getNumber();

        if(!StringUtils.isBlank(number) && !StringUtils.isBlank(form.getSubmittedValue())){
            Cheque cheque = chequeDao.getByNumber(number);
            if(cheque!= null){
                cheque.setDiscount(form.getDiscount());
                chequeDao.update(cheque);
            }

            return actionMapping.findForward("success");
        }

        return actionMapping.getInputForward();
    }
}
